package me.disenia.labs.android.enchingatown_free;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;

public class TwittHandler extends Activity {
	private final static Handler mTwitterHandler = new Handler();
	private SharedPreferences prefs;
	private static String tweetMsg;
	private static String strBadgeDescription;
	private static String badgeId;
	
	private TextView loginStatus;
	private TextView badge_description;
	//private Button clearCredentials;
	private EditText edtInput;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.twitter);
		
		this.prefs = PreferenceManager.getDefaultSharedPreferences(this);
		
		Bundle extras = getIntent().getExtras();
		String txt = "";
		String desc = "";
		//String bdgid = "";
		if (extras != null) {
			txt = extras.getString(MainActivity.TWEET_TEXT);
			desc = extras.getString(MainActivity.BADGE_DESCRIPTION);
			badgeId = extras.getString(MainActivity.BADGE_ID);
		} else {
			try {
				finalize();
			} catch (Throwable e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		tweetMsg = txt;
		strBadgeDescription = desc;
		
		edtInput = (EditText) findViewById(R.id.edtInput);
		badge_description = (TextView) findViewById(R.id.badge_description);
		
		edtInput.setText(tweetMsg);
		badge_description.setText(strBadgeDescription);

		//Toast.makeText(this, txt, 2000);
        loginStatus = (TextView)findViewById(R.id.login_status);
        Button tweet = (Button) findViewById(R.id.btn_tweet);
        //clearCredentials = (Button) findViewById(R.id.btn_clear_credentials);
        
        tweet.setOnClickListener(new OnClickListener() {
            public void onClick(View v) {
            	if (TwitterUtils.isAuthenticated(prefs)) {
            		sendTweet();
            	} else {
    				Intent i = new Intent(getApplicationContext(), PrepareRequestTokenActivity.class);
    				i.putExtra("tweet_msg",edtInput.getText());
    				startActivity(i);
            	}
            }
        });

        //clearCredentials.setOnClickListener(onTweetEnabled);	
        
        updateLoginStatus();
	}

	/*private OnClickListener onTweetEnabled = new OnClickListener() {
        public void onClick(View v) {
        	if (TwitterUtils.isAuthenticated(prefs)) {
        		clearCredentials();
            	updateLoginStatus();
        	} 
        }
    };
    
	private OnClickListener onTweetDisabled = new OnClickListener() {
        public void onClick(View v) {
        	if (!TwitterUtils.isAuthenticated(prefs)){
        		Intent i = new Intent(getApplicationContext(), PrepareRequestTokenActivity.class);
        		i.putExtra("tweet_msg",edtInput.getText());
        		startActivity(i);
        	}
        }
    };*/
		
	final Runnable mUpdateTwitterNotification = new Runnable() {
        public void run() {
        	//Toast.makeText(getBaseContext(), "Tweet sent !", Toast.LENGTH_LONG).show();
        }
    };
	
    @Override
	protected void onResume() {
		super.onResume();
		updateLoginStatus();
	}
	
	public void updateLoginStatus() {
		loginStatus.setText("Select the Social Network where you want to share it : "/* + TwitterUtils.isAuthenticated(prefs)*/);
		/*if (TwitterUtils.isAuthenticated(prefs)){
			clearCredentials.setText("Logout from Twitter");
			clearCredentials.setOnClickListener(onTweetEnabled);
		} else {
			clearCredentials.setText("Login to Twitter");
			clearCredentials.setOnClickListener(onTweetDisabled);
		}*/
	}
	
//	private static String getTweetMsg() {
//		return tweetMsg; // "Tweeting from Android App at " + new Date().toLocaleString();
//	}	
	
	public void sendTweet() {
		Thread t = new Thread() {
	        @Override
			public void run() {
	        	//showCustomNotification();
	        	try {
	        		//TwitterUtils.sendTweet(prefs,edtInput.getText().toString());
	        		//mTwitterHandler.post(mUpdateTwitterNotification);
	        		// http://enchingatown.com/wp-content/themes/enchingatown/ssi/tweet.php
	        		// nTweet=Estoy+%23enchingatown!+y+estoy+en+un+estado+de+No+Son+Enchiladas+http%3A%2F%2Fenchingatown.com%2Fno-son-enchiladas%2F&postToTW=on&idBadge=257
	        		/*
	        		nTweet="Estoy #enchingatown! y estoy en un estado de No Son Enchiladas http://enchingatown.com/no-son-enchiladas/";
	        		postToTW=on
	        		idBadge=257
	        		*/
	        		postData();
	        		//showCustomNotification();
				} catch (Exception ex) {
					ex.printStackTrace();
				}
	        }

	    };
	    t.start();
	}

	public void postData() throws Exception {
	    // Create a new HttpClient and Post Header
	    HttpClient httpclient = new DefaultHttpClient();
	    
	    String tweetmsg = edtInput.getText().toString();
	    
	 //   HttpPost httppost = new HttpPost("http://enchingatown.com/wp-content/themes/enchingatown/ssi/tweet.php");

	    try {
	        // Add your data
	    	List<NameValuePair> params = new ArrayList<NameValuePair>();
	    	params.add(new BasicNameValuePair("nTweet", tweetmsg));
	        params.add(new BasicNameValuePair("postToTW", "on"));
	        params.add(new BasicNameValuePair("idBadge", badgeId));
	        String paramString = URLEncodedUtils.format(params, "utf-8");
	        HttpGet httpget = new HttpGet("http://enchingatown.com/wp-content/themes/enchingatown/ssi/tweet.php?"+paramString);
	        //httpget.setEntity(new UrlEncodedFormEntity(nameValuePairs));

	        // Execute HTTP Post Request
	        ResponseHandler<String> responseHandler=new BasicResponseHandler();
	        String responseBody = httpclient.execute(httpget, responseHandler);
			//JSONObject response = new JSONObject(responseBody);
	        
	        if (responseBody.equals("e")){
	        	// call Troll Notification
	        	showTrollNotification();
	        	TwitterUtils.sendTweet(prefs,tweetmsg);
        		mTwitterHandler.post(mUpdateTwitterNotification);
	        } else {
	        	// call Boss Notification
	        	showCustomNotification();
	        }
	        //HttpResponse response = httpclient.execute(httpget);
	        
	    } catch (ClientProtocolException e) {
	        // TODO Auto-generated catch block
	    	//showCustomNotification();
	    } catch (IOException e) {
	        // TODO Auto-generated catch block
	    	//showCustomNotification();
	    }
	} 
	// see http://androidsnippets.com/executing-a-http-post-request-with-httpclient
	
	/*private void clearCredentials() {
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		final Editor edit = prefs.edit();
		edit.remove(OAuth.OAUTH_TOKEN);
		edit.remove(OAuth.OAUTH_TOKEN_SECRET);
		edit.commit();
	}*/
	
    private void showCustomNotification(){
    	String ns = Context.NOTIFICATION_SERVICE;
    	NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
    	int icon = R.drawable.like_a_boss;
    	CharSequence tickerText = "Like a boss!";
    	long when = System.currentTimeMillis();

    	Notification notification = new Notification(icon, tickerText, when);
    	notification.defaults |= Notification.FLAG_AUTO_CANCEL;
    	Context context = getApplicationContext();
    	CharSequence contentTitle = "Like a boss! ";
    	CharSequence contentText = "Has hecho check-in.";
    	Intent notificationIntent = new Intent(this, MainActivity.class);
    	PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    	notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    	final int HELLO_ID = 1;

    	mNotificationManager.notify(HELLO_ID, notification);
    	/*String ns = Context.NOTIFICATION_SERVICE;
    	NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
    	Notification notification = new Notification();
    	
    	RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification_layout);
    	contentView.setImageViewResource(R.id.image, R.drawable.like_a_boss);
    	contentView.setTextViewText(R.id.text, "Has hecho check-in.");
    	notification.contentView = contentView;
    	
    	Intent notificationIntent = new Intent(this, MainActivity.class);
    	PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    	notification.contentIntent = contentIntent;
    	final int HELLO_ID = 1;
    	mNotificationManager.notify(HELLO_ID, notification);*/
    	
    	finish();
    
    }

    private void showTrollNotification(){
    	String ns = Context.NOTIFICATION_SERVICE;
    	NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
    	int icon = R.drawable.troll;
    	CharSequence tickerText = "Check-ins son cada 3hs!";
    	long when = System.currentTimeMillis();

    	Notification notification = new Notification(icon, tickerText, when);
    	notification.defaults |= Notification.FLAG_AUTO_CANCEL;
    	Context context = getApplicationContext();
    	CharSequence contentTitle = "Problem?";
    	CharSequence contentText = "No ganaste badge.";
    	Intent notificationIntent = new Intent(this, MainActivity.class);
    	PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

    	notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
    	final int HELLO_ID = 1;

    	mNotificationManager.notify(HELLO_ID, notification);
    	/*String ns = Context.NOTIFICATION_SERVICE;
    	NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
    	Notification notification = new Notification();
    	
    	RemoteViews contentView = new RemoteViews(getPackageName(), R.layout.custom_notification_layout);
    	contentView.setImageViewResource(R.id.image, R.drawable.troll);
    	contentView.setTextViewText(R.id.text, "Check-ins son cada 3hs. No hay badge.");
    	notification.contentView = contentView;
    	
    	Intent notificationIntent = new Intent(this, MainActivity.class);
    	PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    	notification.contentIntent = contentIntent;
    	final int HELLO_ID = 1;
    	mNotificationManager.notify(HELLO_ID, notification);*/
    	
    	finish();
    }
}